import { useEffect, useState, useCallback } from 'react'

/**
 * @description 监听dom元素的变化
 * @param ref
 * @returns {unknown}
 */
const useResizeObserver = (ref) => {
  const [dimensions, setDimensions] = useState(null)

  const handleResize = useCallback((entries) => {
    const { width, height } = entries[0].contentRect
    setDimensions({ width, height })
  }, [])

  useEffect(() => {
    const observer = new ResizeObserver(handleResize)

    if (ref?.current) {
      observer.observe(ref.current)
    }

    return () => {
      observer.disconnect()
    }
  }, [ref, handleResize])

  return dimensions // { width, height }
}

export default useResizeObserver
